#!/bin/sh

#############
#A utility to batch convert WAV files into MP3 files using the 1st track and recording the TC stamp in the id3 tags
#
#Written by Wandering Ear
#http://wanderingear.net
# Copyright ©2016 Wandering Ear
#
#
#This program is free software: you can redistribute it and/or modify
#it under the terms of the GNU General Public License as published by
#the Free Software Foundation, either version 3 of the License, or
#(at your option) any later version.
#
#This program is distributed in the hope that it will be useful,
#but WITHOUT ANY WARRANTY; without even the implied warranty of
#MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#GNU General Public License for more details.
#
#You should have received a copy of the GNU General Public License
#along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
############
# Set variables and loop through each file
echo "-- Start -- $(DATE)"

# Set path to included binaries
lib_dir="${PWD}"

# Set path to App Directory
app_dir=${PWD}
app_dir=$(dirname "${app_dir}")
app_dir=$(dirname "${app_dir}")
app_dir=$(dirname "${app_dir}")

# Set path to ffmpeg
if [ -e "${lib_dir}/ffmpeg" ];
then ffmpeg="${lib_dir}/ffmpeg"
elif [ -e "/Applications/ffmpeg" ]; then ffmpeg="/Applications/ffmpeg"
elif [ -e "/Applications/ffmpeg/ffmpeg" ]; then ffmpeg="/Applications/ffmpeg/ffmpeg"
elif [ -e "${app_dir}/ffmpeg" ]; then ffmpeg="${app_dir}/ffmpeg"
elif [ -e "/usr/local/bin/ffmpeg" ]; then ffmpeg="/usr/local/bin/ffmpeg"
else echo "Cannot locate ffmpeg binary"
fi

# Read files loop
for in_file in "$@"
do
if [ -e "$in_file" ]
then
echo "Reading file: ${in_file}"

# Set output file path and name
out_file="${in_file%.WAV}"
out_file="${out_file%.wav}"
out_file="${out_file}.mp3"

# Use BWFMETAEDIT to export metadata and clean into variables
"${lib_dir}/bwfmetaedit" --out-iXML-xml "$in_file"
"${lib_dir}/bwfmetaedit" --out-core-xml "$in_file"
if [ -e "${in_file}.Core.xml" ]
then
    samples_since_midnight=$("${lib_dir}/xml" sel -t -v '/conformance_point_document/File/Core/TimeReference[1]' "${in_file}.Core.xml")
    if [ -z "$samples_since_midnight" ]
    then
        samples_since_midnight=$("${lib_dir}/xml" sel -t -v '/BWFXML/SPEED/TIMESTAMP_SAMPLES_SINCE_MIDNIGHT[1]' "${in_file}.iXML.xml")
    fi
    ubits=$("${lib_dir}/xml" sel -t -v '/BWFXML/UBITS[1]' "${in_file}.iXML.xml")
    if [ -z "$ubits" ]
    then
        ubits=$("${lib_dir}/xml" sel -t -v '/conformance_point_document/File/Core/Description[1]' "${in_file}.Core.xml" | grep 'UBITS')
        ubits=${ubits##*UBITS=$}
        ubits=$(printf "%.8s" ${ubits})
    fi
else echo "Error reading Core XML data"
fi
if [ -e "${in_file}.iXML.xml" ]
then
    timecode_rate=$("${lib_dir}/xml" sel -t -v '/BWFXML/SPEED/TIMECODE_RATE[1]' "${in_file}.iXML.xml")
    timecode_flag=$("${lib_dir}/xml" sel -t -v '/BWFXML/SPEED/TIMECODE_FLAG[1]' "${in_file}.iXML.xml")
    sample_rate=$("${lib_dir}/xml" sel -t -v '/conformance_point_document/File/Core/CodingHistory[1]' "${in_file}.Core.xml")
    sample_rate=${sample_rate##*F=}
    sample_rate=${sample_rate%%,*}
    if [ -z "$sample_rate" ]
    then
        sample_rate=$("${lib_dir}/xml" sel -t -v '/BWFXML/SPEED/TIMESTAMP_SAMPLE_RATE[1]' "${in_file}.iXML.xml")
    fi
    if [ -z "$sample_rate" ]
    then
        sample_rate=$("${lib_dir}/xml" sel -t -v '/BWFXML/BEXT/BWF_CODING_HISTORY[1]' "${in_file}.iXML.xml")
        sample_rate=${sample_rate##*F=}
        sample_rate=${sample_rate%%,*}
    fi
    scene=$("${lib_dir}/xml" sel -t -v '/BWFXML/SCENE[1]' "${in_file}.iXML.xml")
    take=$("${lib_dir}/xml" sel -t -v '/BWFXML/TAKE[1]' "${in_file}.iXML.xml")
    tape=$("${lib_dir}/xml" sel -t -v '/BWFXML/TAPE[1]' "${in_file}.iXML.xml")
else echo "Error reading iXML data"
fi

# Check to make sure individual metadata items were read
if [ -z "$samples_since_midnight" ]; then echo "Error reading Timecode Stamp"; fi
if [ -z "$timecode_rate" ]; then echo "Error reading Timecode Rate"; fi
if [ -z "$timecode_flag" ]; then echo "Error reading Timecode Flag"; fi
if [ -z "$ubits" ]; then echo "Error reading User Bits"; fi
if [ -z "$sample_rate" ]; then echo "Error reading Sample Rate"; fi
if [ -z "$scene" ]; then echo "Error reading Scene"; fi
if [ -z "$take" ]; then echo "Error reading Take"; fi
if [ -z "$tape" ]; then echo "Error reading Sound Roll"; fi

# Check frame rate, Calculate and form TC stamp
if [ -z "$samples_since_midnight" ]; then echo "Error - cannot calculate TC Value - SSM"; else
if [ -z "$timecode_rate" ]; then echo "Error - cannot calculate TC Value - TCR"; else
if [ -z "$sample_rate" ]; then echo "Error - cannot calculate TC Value - SR";
else

    tc_stamp=$((${samples_since_midnight}*${timecode_rate}/${sample_rate}))
# 23.976 fps
    if [ $timecode_rate = '24000/1001' ]
        then tc_stamp=$(printf '%02d:%02d:%02d:%02d\n' $(($tc_stamp/86400)) $(($tc_stamp%86400/1440)) $(($tc_stamp%1440/24)) $(($tc_stamp%24)))
        frame_rate="23.976-ND"
# 24 fps
    elif [ $timecode_rate = '24000/1000' ]
        then tc_stamp=$(printf '%02d:%02d:%02d:%02d\n' $(($tc_stamp/86400)) $(($tc_stamp%86400/1440)) $(($tc_stamp%1440/24)) $(($tc_stamp%24)))
        frame_rate="24-ND"
# 25 fps
    elif [ $timecode_rate = '25/1' ]
        then tc_stamp=$(printf '%02d:%02d:%02d:%02d\n' $(($tc_stamp/90000)) $(($tc_stamp%90000/1500)) $(($tc_stamp%1500/25)) $(($tc_stamp%25)))
        frame_rate="25-ND"
# 29.97 ND
    elif [ $timecode_rate = '30000/1001' ] & [ $timecode_flag = 'NDF' ]
        then tc_stamp=$(printf '%02d:%02d:%02d:%02d\n' $(($tc_stamp/108000)) $(($tc_stamp%108000/1800)) $(($tc_stamp%1800/30)) $(($tc_stamp%30)))
        frame_rate="29.97-ND"
# 29.97 DF
    elif [ $timecode_rate = '30000/1001' ] & [ $timecode_flag = 'DF' ]
        then
# 1798 frames per minute, 17982 frames per 10 minutes, 107892 frames per hour
        d=$(printf '%d' $(($tc_stamp/17982)))
        m=$(printf '%d' $(($tc_stamp%17982)))
        tc_stamp=$(($tc_stamp+(18*$d)+(2*(($m-2)/1798))))
        tc_stamp=$(printf '%02d:%02d:%02d:%02d' $(((($tc_stamp/30)/60)/60)) $(((($tc_stamp/30)/60)%60)) $((($tc_stamp/30)%60)) $(($tc_stamp%30)))
        frame_rate="29.97-DF"
# 30 fps
    elif [ $timecode_rate = '30000/1000']
        then tc_stamp=$(printf '%02d:%02d:%02d:%02d\n' $(($tc_stamp/108000)) $(($tc_stamp%108000/1800)) $(($tc_stamp%1800/30)) $(($tc_stamp%30)))
        frame_rate="30-ND"
    fi

fi
fi
fi

#Form ID3 Tags
id3_title='SC='${scene}' TK='${take}
id3_artist='TC='${tc_stamp}' UB='${ubits}
id3_album='FR='${frame_rate}' TAPE='${tape}

#Convert WAV to MP3
echo "Converting"

"${ffmpeg}" -v 24 -stats -y -i "${in_file}" -af "pan=1c|c0=c0" -codec:a libmp3lame -b:a 96k -id3v2_version 3 -f mp3 -metadata coding_history="" -metadata title="${id3_title}" -metadata artist="${id3_artist}" -metadata album="${id3_album}" -metadata encoded_by="" -metadata originator_reference="" -metadata date="" -metadata comment="" "${out_file}"

# Cleanup
echo "Cleaning Up"
if [ -e "${in_file}.iXML.xml" ]; then rm "${in_file}.iXML.xml"; fi
if [ -e "${in_file}.Core.xml" ]; then rm "${in_file}.Core.xml"; fi

fi
done
echo "***********"
echo "Done"
